package cn.matezk.iot;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import org.apache.log4j.Logger;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class SqliteUtils {
    private static Logger logger = Logger.getLogger(SqliteUtils.class);

    static {
        String sql = "CREATE TABLE IF NOT EXISTS t_printer (" +
                "device_id TEXT PRIMARY KEY," +
                "product_id TEXT," +
                "device_name TEXT," +
                "print_time DATE NOT NULL" +
                ");";
        try {
            Db.use().execute(sql);
        } catch (SQLException e) {
            logger.error(e);
        }
    }

    public static int addOne(String productId, String deviceName) throws SQLException {
        List<Entity> list = Db.use().findAll(Entity.create("t_printer").set("device_name", deviceName));
        for (Entity e : list) {
            Db.use().del(e);
        }
        Db.use().insert(Entity.create("t_printer")
                .set("device_id", productId.concat("/").concat(deviceName))
                .set("product_id", productId)
                .set("device_name", deviceName)
                .set("print_time", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN)));
        return count();
    }

    public static int count() throws SQLException {
        return Db.use().queryNumber("select count(1) from t_printer where print_time > current_date").intValue();
    }
}
